// client.c - Unix本地套接字客户端实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>

#define SOCKET_PATH "/tmp/my_unix_socket"  // 套接字文件路径
#define BUFFER_SIZE 1024                  // 缓冲区大小

int main() {
    int client_fd;
    struct sockaddr_un server_addr;
    char buffer[BUFFER_SIZE] = {0};
    int bytes_sent, bytes_received;

    // 创建套接字
    client_fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (client_fd == -1) {
        perror("socket创建失败");
        exit(EXIT_FAILURE);
    }

    // 清除并设置地址结构
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sun_family = AF_UNIX;
    strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);

    // 连接到服务器
    if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("connect失败");
        close(client_fd);
        exit(EXIT_FAILURE);
    }

    printf("已连接到服务器，输入消息（输入'exit'退出）:\n");

    while (1) {
        // 从标准输入读取消息
        memset(buffer, 0, sizeof(buffer));
        fgets(buffer, sizeof(buffer) - 1, stdin);
        buffer[strcspn(buffer, "\n")] = 0;  // 去除换行符

        // 发送消息到服务器
        bytes_sent = send(client_fd, buffer, strlen(buffer), 0);
        if (bytes_sent == -1) {
            perror("send失败");
            break;
        }

        // 检查是否退出
        if (strcmp(buffer, "exit") == 0) {
            break;
        }

        // 接收服务器回显
        bytes_received = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
        if (bytes_received == -1) {
            perror("recv失败");
            break;
        } else if (bytes_received == 0) {
            printf("服务器已关闭连接\n");
            break;
        }

        buffer[bytes_received] = '\0';  // 确保字符串以NULL结尾
        printf("服务器回显: %s\n", buffer);
    }

    // 关闭套接字
    close(client_fd);
    printf("客户端已退出\n");

    return 0;
}
